package de.tg.handball;

import java.util.Date;
import java.util.List;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import de.tg.handball.data.DataManager;
import de.tg.handball.util.Util;
import de.tg.handball.xml.RSSFeed;
import de.tg.handball.xml.RSSItem;

public class NewsActivity extends Activity {

	private ListView list;
	private RSSFeed feed = null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.news);

		setTitleColor(getResources().getColor(R.color.tg_title_color));

		String title = getTitle().toString();
		title += " - News";
		setTitle(title);

		feed = DataManager.getInstance().feed;

		if (feed == null) {
			findViewById(R.id.news_no).setVisibility(View.VISIBLE);
			findViewById(R.id.news_liste).setVisibility(View.GONE);
		} else {
			list = (ListView) findViewById(R.id.news_liste);
			NewsAdapter adp = new NewsAdapter(this, feed.getAllItems());
			list.setAdapter(adp);
			list.setOnItemClickListener(new NewsListener(adp));
		}

	}

	private class NewsAdapter extends ArrayAdapter<RSSItem> {

		Activity context = null;

		public NewsAdapter(Activity context, List<RSSItem> objects) {
			super(context, R.layout.news_entry, objects);
			this.context = context;
		}

		public View getView(int pos, View convertView, ViewGroup parent) {
			RSSItem sp = super.getItem(pos);

			if (convertView == null) {
				convertView = context.getLayoutInflater().inflate(
						R.layout.news_entry, null);

			}

			TextView tx = (TextView) convertView
					.findViewById(R.id.news_item_datum);
			Date datum = sp.getPubDate();
			if (datum != null)
				tx.setText(Util.dateForm.format(datum));
			tx = (TextView) convertView.findViewById(R.id.news_item_title);
			tx.setText(sp.getTitle());

			return convertView;
		}
	}

	private class NewsListener implements OnItemClickListener {
		private NewsAdapter newsAdapter = null;

		public NewsListener(NewsAdapter newsAdapter) {
			this.newsAdapter = newsAdapter;
		}

		public void onItemClick(AdapterView<?> arg, View view, int position,
				long id) {
			RSSItem item = newsAdapter.getItem(position);
			if (item != null && item.getLink() != null) {
				Intent myIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(item
						.getLink()));
				startActivity(myIntent);
			}

		}
	}
}
